package curator.discovery;


import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.ServiceProvider;
import org.apache.curator.x.discovery.UriSpec;
import org.apache.curator.x.discovery.details.JsonInstanceSerializer;
import org.apache.curator.x.discovery.strategies.RandomStrategy;
import org.apache.curator.x.discovery.strategies.RoundRobinStrategy;

public class DiscoveryExample
{
	
	public static String zookeeperConnectionString = "192.168.3.62:9090";
	
	public static RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 10);
	
	public static CuratorFramework client = CuratorFrameworkFactory.newClient(zookeeperConnectionString, 10000, 5000, retryPolicy);
	
    private static final String PATH = "/discovery/example";

    public static void main(String[] args) throws Exception
    {
        client.start();

        JsonInstanceSerializer<InstanceDetails> serializer = new JsonInstanceSerializer<InstanceDetails>(InstanceDetails.class);
        
        ServiceDiscovery<InstanceDetails> serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(PATH).serializer(serializer).build();
        
        serviceDiscovery.start();
        
        UriSpec uriSpec = new UriSpec("{thrift}://192.168.3.62:1234:{1234}");
        
        String serviceName = "test_service";
        
//        ServiceInstance<InstanceDetails> thisInstance = ServiceInstance.<InstanceDetails>builder()
//                .name(serviceName)
//                .port(1234) // in a real application, you'd use a common port
//                .build();
//        serviceDiscovery.registerService(thisInstance);
        
        ServiceProvider<InstanceDetails> provider = serviceDiscovery.serviceProviderBuilder().serviceName(serviceName).providerStrategy(new RandomStrategy<InstanceDetails>()).build();
       
        provider.start();

        ServiceInstance<InstanceDetails> thatInstance = provider.getInstance();
        
        System.out.println(thatInstance);
        
//        assert(thatInstance.toString().compareTo(thisInstance.toString()) == 0);
        
        while(true)
        {
        	Thread.sleep(1000);
        }
    }

}